<template>
  <view class="container d-flex flex-column">
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->
    <view class="form">
      <list-cell :hover="false">
        <view class="form-input w-100 d-flex align-items-center">
          <view class="label">{{ currentLanguageTexts.profilepicture }}</view>
          <view class="input flex-fill">
            <view
              class="form-input w-100 d-flex align-items-center"
              style="position: relative"
            >
              <view class="flex user-box align-items-center">
                <view class="mr-1">
                  <uv-avatar :src="member.avatar" size="60"></uv-avatar>
                </view>
                <view v-if="!member.avatar" class="flex-1">
                  <uv-button
                    size="mini"
                    type="primary"
                    @click="chooseImage"
                    :customStyle="{ color: 'rgb(90, 91, 92)' }"
                  >
                    {{ currentLanguageTexts.Changeavatar }}
                  </uv-button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </list-cell>
      <list-cell :hover="false">
        <view class="form-input w-100 d-flex align-items-center">
          <view class="label">{{ currentLanguageTexts.name }}</view>
          <view class="input flex-fill">
            <input
              type="nickname"
              :placeholder="currentLanguageTexts.PleaseName"
              placeholder-class="text-color-assist font-size-base"
              v-model="member.nickname"
            />
          </view>
        </view>
      </list-cell>
      <list-cell :hover="false">
        <view
          class="form-input w-100 d-flex align-items-center"
          style="position: relative"
        >
          <view class="label">{{ currentLanguageTexts.phone }}</view>
          <view class="input flex-fill">
            <input type="text" v-model="member.mobile" disabled />
          </view>
        </view>
      </list-cell>
      <list-cell :hover="false">
        <view class="form-input w-100 d-flex align-items-center">
          <view class="label">{{ currentLanguageTexts.gender }}</view>
          <view class="input flex-fill">
            <!-- <view class="radio-group">
              <view
                class="radio"
                :class="{ checked: member.gender == '0' }"
                style="margin-right: 10rpx"
                @tap="member.gender = 0"
                >先生</view
              >
              <view
                class="radio"
                :class="{ checked: member.gender == '1' }"
                @tap="member.gender = 1"
                >女士</view
              >
            </view> -->
            <uv-radio-group
              v-model="member.gender"
              :customStyle="{ gap: '20rpx' }"
            >
              <uv-radio :name="0">{{ currentLanguageTexts.Mr }}</uv-radio>
              <uv-radio :name="1">{{ currentLanguageTexts.Ms }}</uv-radio>
            </uv-radio-group>
          </view>
        </view>
      </list-cell>
      <list-cell :hover="false" :arrow="!member.birthday">
        <view class="form-input w-100 d-flex align-items-center">
          <view class="label">{{ currentLanguageTexts.birthday }}</view>
          <view class="input flex-fill" @click="datetimePicker.open()">
            {{
              member.birthday
                ? formatDateTime(member.birthday, 'YYYY-MM-DD')
                : currentLanguageTexts.empty
            }}
            <uv-datetime-picker
              ref="datetimePicker"
              mode="date"
              v-model="member.birthday"
              :confirmText="currentLanguageTexts.confirm"
              :cancelText="currentLanguageTexts.cancel"
              :min-date="minDate"
            >
            </uv-datetime-picker>
          </view>
        </view>
      </list-cell>
      <list-cell :hover="false" last>
        <view class="form-input w-100 d-flex align-items-center">
          <view class="label">{{ currentLanguageTexts.Joinedon }}</view>
          <view class="input flex-fill">
            <input
              type="text"
              :value="formatDateTime(member.createTime)"
              disabled
            />
          </view>
        </view>
      </list-cell>
    </view>
    <view class="btn-box d-flex align-items-center just-content-center mt-2">
      <uv-button
        type="primary"
        class="save-btn"
        @tap="save"
        :custom-style="{
          borderRadius: '40rpx',
          fontWeight: 'bold',
          color: '#5A5B5C',
        }"
        >{{ currentLanguageTexts.save }}</uv-button
      >
    </view>
    <view
      class="text-color-assist text-center font-size-sm mt-3"
      @tap="loginout"
      >{{ currentLanguageTexts.exit }}</view
    >
    <uv-modal
      ref="modal"
      :content="currentLanguageTexts.ConfirmIn"
      showCancelButton
      @confirm="logout"
      confirmColor="#000"
      align="center"
      :confirmText="currentLanguageTexts.confirm"
      :cancelText="currentLanguageTexts.cancel"
    >
    </uv-modal>
    <uv-toast ref="uToast"></uv-toast>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { formatDateTime } from '@/utils/util';
import { userEdit } from '@/api/user';
import { VUE_APP_UPLOAD_URL, TENANT_ID } from '@/config';
import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs';

const main = useMainStore();
const uToast = ref();
const modal = ref();
const { openid, lang, currentLanguageTexts } = storeToRefs(main);

const title = ref(currentLanguageTexts.value.UserSettings);
//const currentDate = ref('')
const datetimePicker = ref();
const date = ref('');
const member = ref({});
const minDate = dayjs('1960-01-01').valueOf();

onLoad(() => {
  member.value = main.member;
  //this.$util
  member.value.createTime = member.value.createTime;
});
onShow(() => {
  date.value = getDate({ format: true });
});

const startDate = computed(() => {
  return getDate('');
});
const endDate = computed(() => {
  return getDate('end');
});
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      chooseavatar(res);
    },
  });
};

const chooseavatar = (e) => {
  console.log(e);
  uni.uploadFile({
    url: VUE_APP_UPLOAD_URL,
    filePath: e.tempFilePaths[0],
    name: 'file',
    header: {
      Authorization: 'Bearer ' + uni.getStorageSync('accessToken'),
      lang: lang.value,
      'tenant-id': TENANT_ID,
    },
    success(uploadFileResult) {
      if (uploadFileResult) {
        const upload = JSON.parse(uploadFileResult.data);
        member.value.avatar = upload.data;
      }
    },
    fail(e) {},
  });
};
const getDate = (type) => {
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();

  if (type === 'start') {
    year = year - 60;
  } else if (type === 'end') {
    year = year + 2;
  }
  month = month > 9 ? month : '0' + month;
  day = day > 9 ? day : '0' + day;
  return `${year}-${month}-${day}`;
};

const save = async () => {
  let data = await userEdit({
    nickname: member.value.nickname,
    mobile: member.value.mobile,
    gender: member.value.gender,
    birthday: member.value.birthday,
    avatar: member.value.avatar,
  });
  if (data) {
    const member2 = Object.assign(main.member, member.value);
    main.SET_MEMBER(member2);
    uni.showToast({
      title: currentLanguageTexts.value.Successfullysaved,
      icon: 'success',
    });
  }
};
const loginout = () => {
  modal.value.open();
};
const logout = () => {
  uni.removeStorageSync('userinfo');
  uni.removeStorageSync('accessToken');
  main.SET_MEMBER({});
  main.SET_TOKEN('');
  main.SET_ADDRESS({});
  main.SET_ADDRESSES({});
  uToast.value.show({
    message: currentLanguageTexts.value.exited,
    type: 'success',
  });
  main.SET_RETURN(true);
  setTimeout(function () {
    uni.reLaunch({
      url: '/pages/components/pages/login/login',
    });
  }, 2000);
};
</script>

<style lang="scss" scoped>
page {
  height: 100%;
}

.form {
  border-radius: 8rpx;
}

.form-input {
  .label {
    width: 160rpx;
    font-size: $font-size-base;
    color: $text-color-base;
  }

  .input {
  }

  .radio-group {
    display: flex;
    justify-content: flex-start;

    .radio {
      padding: 10rpx 30rpx;
      border-radius: 6rpx;
      border: 2rpx solid $text-color-assist;
      color: $text-color-assist;
      font-size: $font-size-base;

      &.checked {
        background-color: $color-primary;
        color: $text-color-white;
        border: 2rpx solid $color-primary;
      }
    }
  }
}

.btn-box {
  // height: calc((100vh - 40rpx) / 2);
}
.save-btn {
  width: 90%;
  border-radius: 50rem !important;
  font-size: $font-size-lg;
}
.logout-btn {
  width: 90%;
  border-radius: 50rem !important;
  font-size: $font-size-lg;
  background-color: rgb(237, 81, 29);
}
</style>
